//
//  DataBaseManeger.m
//  LoveCar
//
//  Created by dllo on 16/4/1.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "DataBaseManeger.h"

@implementation DataBaseManeger

+(DataBaseManeger *)sharaInstance{
    static DataBaseManeger *db = nil;
    if (!db) {
        db = [[DataBaseManeger alloc] init];
    }
    return db;
}

- (void)openDB{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSLog(@"%@.....", path);
    // 数据库路径
    NSString *dbPath = [path stringByAppendingPathComponent:@"Manger.db"];
    self.db = [FMDatabase databaseWithPath:dbPath];
    BOOL result = [_db open];
    if (result) {
        NSLog(@"数据库成功");
    }else{
        NSLog(@"失败");
    }
}

- (void)closeDB{
    [self.db close];
}

- (void)createTable{
    // 主键 primary 可以(用来唯一标识每一条数据)
    // 自增 AUTOINCREMENT
    NSString *createSQL = @"CREATE TABLE IF NOT EXISTS forum(num INTEGER PRIMARY KEY AUTOINCREMENT,  distance FLOAT, month TEXT, count TEXT)";
    [self execSQL:createSQL message:@"创建表"];
}

#pragma mark - 文章
- (NSMutableArray *)selectAll{
//    static NSMutableArray *arr = nil;
//    if (arr) {
      NSMutableArray *arr = [NSMutableArray array];
//    }
    arr = [NSMutableArray array];
    NSString *selectSQL = @"SELECT * FROM forum";
    FMResultSet *set = [_db executeQuery:selectSQL];
    while ([set next]) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:[set stringForColumn:@"distance"] forKey: @"distance"];
        [dic setObject:[set stringForColumn:@"count"] forKey:@"count"];
        [dic setObject:[set stringForColumn:@"month"] forKey:@"month"];
        [arr addObject:dic];
    }
    return arr;
}


-(void)insertDistance:(NSInteger)sum Time:(NSInteger)count Data:(NSString*)month
{
//    BOOL  result  = [self isCollected:month];
//    if (result) {
        NSString *str=[NSString stringWithFormat:@"INSERT INTO forum (distance, month, count) VALUES('%ld', '%@','%ld')",(long)sum, month, (long)count];
        [self execSQL:str message:@"插入"];
//        [[NSNotificationCenter defaultCenter]postNotificationName:@"collectionSuccess" object:nil];
//    }else{
//        
//    }
}

-(BOOL)isCollected:(NSString *)month
{
    NSString *selectSQL=@"SELECT * FROM forum";
    FMResultSet * set =  [self.db executeQuery:selectSQL];
    //遍历获取每个数据  如果里面已经保存了相同的id 就返回YES  如果保存就返回NO
    while ([set next]){
        NSString *str=[set stringForColumn:@"month"];
        if ([month isEqualToString:str]) {
            return YES;
        }
    }
    return NO;
}

- (void)deleteMovieByMonth:(NSString *)month{
    NSString *deleteSQL = [NSString stringWithFormat:@"DELETE FROM forum WHERE month = '%@'",month];
    [self execSQL:deleteSQL message:@"DELETE"];
}

- (void)execSQL:(NSString *)sql message:(NSString *)mes{
    BOOL result = [_db executeUpdate:sql];
    if (result) {
        NSLog(@"%@成功", mes);
    }else{
        NSLog(@"%@失败", mes);
    }
}


@end
